package com.chj.exchange.direct;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 普通的消费者
 */
public class NormalConsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("10.200.169.5");
        connectionFactory.setVirtualHost("chj_vhost");
        connectionFactory.setUsername("chj");
        connectionFactory.setPassword("123456");
        // 创建连接
        Connection connection = connectionFactory.newConnection();
        final Channel channel = connection.createChannel();
        // 在信道中设置交换器
        channel.exchangeDeclare(DirectProducer.EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        // 申明队列（放在消费者中去做）
        String queueName = "queue-hankin01";
        channel.queueDeclare(queueName, false, false, false, null);
        //绑定：将队列(queuq-king)与交换器通过 路由键 绑定(king)
        String routeKey ="hankin01";
        channel.queueBind(queueName,DirectProducer.EXCHANGE_NAME,routeKey);
        System.out.println("waiting for message ......");
        // 申明一个消费者
        final DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body,"UTF-8");
                System.out.println("Received["+envelope.getRoutingKey()+"]"+message);
            }
        };
        // 消息者正是开始在指定队列上消费。(queue-hankin01)
        // TODO 这里第二个参数是自动确认参数，如果是true则是自动确认
        channel.basicConsume(queueName,true,consumer);
    }
}
